package com.tdam2011.grupo05.ui.activities.message;

import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.control.adapters.MessageCursorAdapter;
import com.tdam2011.grupo05.database.content.TdamContentProvider;
import com.tdam2011.grupo05.entities.message.MessageWeb;
import com.tdam2011.grupo05.entities.message.MessageWeb.State;
import com.tdam2011.grupo05.entities.message.MessageWeb.Type;
import com.tdam2011.grupo05.entities.thread.ThreadWeb;

public class MessageListFragment extends ListFragment implements
		OnClickListener, LoaderCallbacks<Cursor> {

	private static final String TAG = "MessageListFragment";

	interface MensajeCallback {
		void sendMessage(MessageWeb messageWeb, ThreadWeb threadWeb);

		void deleteMessage(long idMessage);

		void backToThreads();
	}

	private static final String[] PROJECTION = { MessageWeb.COL_ID,
			MessageWeb.COL_ID_THREAD, MessageWeb.COL_RESULT,
			MessageWeb.COL_STATE, MessageWeb.COL_TIMESTAMP,
			MessageWeb.COL_TEXT, MessageWeb.COL_TYPE };

	private MensajeCallback listener;

	private MessageCursorAdapter mAdapter;
	private ThreadWeb threadWeb;

	private Button mButtonSend;
	private EditText mEditTextMessage;
	private TextView mTextViewContact;
	private ImageView mImageViewBar;

	private View.OnClickListener imageAction = new OnClickListener() {

		@Override
		public void onClick(View v) {
			listener.backToThreads();
		}
	};

	@Override
	public void onAttach(Activity activity) {

		super.onAttach(activity);
		listener = (MensajeCallback) activity;

		mAdapter = new MessageCursorAdapter(getActivity(),
				R.layout.message_item_outgoing, null,
				new String[] { MessageWeb.COL_TEXT },
				new int[] { R.id.txt_web_message }, 0);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_message_web, container,
				false);
		mButtonSend = (Button) view.findViewById(R.id.btn_menssage_send);
		mEditTextMessage = (EditText) view
				.findViewById(R.id.txt_menssage_to_send);
		mTextViewContact = (TextView) view.findViewById(R.id.texto_titulo);
		mImageViewBar = (ImageView) view
				.findViewById(R.id.imagen_mensaje_contacto);
		mImageViewBar.setOnClickListener(imageAction);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);

		getListView().setOnItemLongClickListener(longClickAction);
		getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		getListView().setStackFromBottom(true);
		mButtonSend.setOnClickListener(this);
		setListAdapter(mAdapter);
		mTextViewContact.setText(threadWeb.getName());
		getLoaderManager().initLoader(0, null, this);
	}

	// send button
	@Override
	public void onClick(View v) {

		MessageWeb m = new MessageWeb();
		m.setText(mEditTextMessage.getText().toString());
		m.setIdThread(threadWeb.getId());
		m.setTimestamp(new Date());
		m.setState(State.UNSENDED);
		m.setType(Type.OUTGOING);
		if (listener != null) {
			listener.sendMessage(m, threadWeb);
		}
		mEditTextMessage.setText("");
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		StringBuilder selection = new StringBuilder(MessageWeb.COL_ID_THREAD);
		selection.append("=");
		selection.append(threadWeb.getId());
		Log.d(TAG, "thread: " + threadWeb + " name=" + threadWeb.getName());
		return new CursorLoader(getActivity(),
				TdamContentProvider.MESSAGE_CONTENT_URI, PROJECTION,
				selection.toString(), null, "1");
	}

	private AdapterView.OnItemLongClickListener longClickAction = new AdapterView.OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos,
				long id) {
			showDialogInfo(pos);
			return true;
		}
	};

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		mAdapter.swapCursor(cursor);
	}

	protected void showDialogInfo(final int pos) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(getResources()
				.getString(R.string.dialog_delete_option));
		builder.setMessage(R.string.dialog_delete_message);
		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				CursorWrapper cw = (CursorWrapper) mAdapter.getItem(pos);
				long id = cw.getLong(cw.getColumnIndex(MessageWeb.COL_ID));
				if (listener != null) {
					listener.deleteMessage(id);
					Log.d(TAG, "message delete=" + id);
				}
				dialog.dismiss();
			}
		});
		builder.setCancelable(true);
		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mAdapter.swapCursor(null);
	}

	public ThreadWeb getThreadWeb() {
		return threadWeb;
	}

	public void setThreadWeb(ThreadWeb threadWeb) {
		this.threadWeb = threadWeb;
	}

}
